84. Largest Rectangle in Histogram - LeetCode Solution


Array Stack

Python Code:

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        
        if len(heights) == 0:
            return 0
        
        stack = []

        left = []
        right = []

        stackr = []

        for i in range(len(heights)):

            while len(stack) != 0 and heights[stack[-1]] >= heights[i]:
                stack.pop()

            if len(stack) ==0 :
                left.append(0)
            else:
                left.append(stack[-1]+1)

            stack.append(i)


            while len(stackr) != 0 and heights[stackr[-1]] >= heights[len(heights) - i - 1]:
                stackr.pop()

            if len(stackr) ==0 :
                right.append(len(heights) - 1)
            else:
                right.append(stackr[-1] -1 )

            stackr.append(len(heights) - i - 1 )


        print("Left", left)
        print("right", right[::-1])

        right = right[::-1]

        ans =[]

        for i in range(len(right)):
            ans.append((right[i] - left[i] +1) * heights[i])



        return max(ans)


Comments

Submit
0 Comments
More Questions

1371C - A Cookie for You
430B - Balls Game
1263A - Sweet Problem
1332B - Composite Coloring
254A - Cards with Numbers
215A - Bicycle Chain
1288B - Yet Another Meme Problem
1201C - Maximum Median
435A - Queue on Bus Stop
1409B - Minimum Product
723B - Text Document Analysis
1471C - Strange Birthday Party
1199A - City Day
1334A - Level Statistics
67B - Restoration of the Permutation
1734A - Select Three Sticks
1734B - Bright Nice Brilliant
357B - Flag Day
937A - Olympiad
1075A - The King's Race
1734C - Removing Smallest Multiples
1004C - Sonya and Robots
922A - Cloning Toys
817A - Treasure Hunt
1136B - Nastya Is Playing Computer Games
1388A - Captain Flint and Crew Recruitment
592B - The Monster and the Squirrel
1081A - Definite Game
721C - Journey
1400A - String Similarity